package com.runen.infinitemovement.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.WebViewH5Entity;
import com.runen.infinitemovement.model.enums.ActivityCompat;
import com.runen.infinitemovement.widget.popupwind.SharePoppupWindow;
import com.runen.infinitemovement.widget.popupwind.SportsPoppupWindow;
import com.runen.rxnetlibrary.utils.JsonUtils;
import com.runen.rxnetlibrary.utils.LogUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Create by LiaoDuanHong
 * Create on 2020/10/14 16:11
 */
public class WebActivity extends BaseActivity {
    private static WebActivity activity;
    @BindView(R.id.web_view)
    WebView webView;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.top_btn_left)
    Button topBtnLeft;
    @BindView(R.id.top_title)
    TextView topTitle;

    private UploadHandler mUploadHandler;
    private ValueCallback<Uri[]> mUploadMessageForAndroid5;
    public final static int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 2;
    private MyChromeViewClient myChromeViewClient = new MyChromeViewClient();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_web;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        activity = this;
        String linkUrl = getIntent().getStringExtra("LINK_URL");
        int flag = getIntent().getIntExtra("flag", 0);
        if (flag == 1) {
            llTitle.setVisibility(View.VISIBLE);
            topTitle.setText("用户协议");
        } else if (flag == 2) {
            llTitle.setVisibility(View.VISIBLE);
            topTitle.setText("隐私协议");
        } else {
            llTitle.setVisibility(View.GONE);
        }
        // 设置WebView的客户端
        webSetting(webView);
        webView.loadUrl(linkUrl);
//        webView.setOnKeyListener(new View.OnKeyListener() {
//            @Override
//            public boolean onKey(View v, int keyCode, KeyEvent event) {
//                if (keyCode == KeyEvent.KEYCODE_BACK) {
//                    if (webView.canGoBack()) {  //表示按返回键时的操作8
//                        webView.goBack();   //后退
////                    webview.goForward();//前进
//                        return true;    //已处理
//                    }
//                }
//                return false;
//            }
//        });
    }


    /**
     * WebView设置参数
     *
     * @param webView
     */
    @SuppressLint("SetJavaScriptEnabled")
    private void webSetting(WebView webView) {
        WebSettings settings = webView.getSettings();
        settings.setDomStorageEnabled(true);
//        settings.setLoadWithOverviewMode(true);
//        settings.setUseWideViewPort(true);
        settings.setJavaScriptEnabled(true);
//        settings.setLoadWithOverviewMode(true);
        settings.setSupportZoom(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
//        settings.setAllowFileAccess(true);// 设置允许访问文件数据
//        settings.setAllowFileAccessFromFileURLs(true);
        settings.setSupportMultipleWindows(true);
        settings.setBlockNetworkImage(false);//同步请求图片
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setDomStorageEnabled(true);
        settings.setDefaultTextEncodingName("UTF-8");
        settings.setAllowContentAccess(true); // 是否可访问Content Provider的资源，默认值 true
        settings.setAllowFileAccess(true);    // 是否可访问本地文件，默认值 true
        // 是否允许通过file url加载的Javascript读取本地文件，默认值 false
        settings.setAllowFileAccessFromFileURLs(false);
        // 是否允许通过file url加载的Javascript读取全部资源(包括文件,http,https)，默认值 false
        settings.setAllowUniversalAccessFromFileURLs(false);
//        webView.setWebChromeClient(new WebViewClientLoad());
        webView.setWebChromeClient(myChromeViewClient);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }

        });
        webView.addJavascriptInterface(new MyJavascriptInterface(), "android");
    }

    /**
     * 接口回调
     */
    private static class WebViewClientLoad extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            activity.showDialog();
            if (newProgress == 100) {
                activity.dismissDialog();
            }
            super.onProgressChanged(view, newProgress);
        }
    }

    //要用来被js调用的java对象
    public static class MyJavascriptInterface {
        @JavascriptInterface
        public void close() {
            onClose();
        }

        @JavascriptInterface
        public void showDialog() {
//            EventBus.getDefault().post(new EventWebEntity(3));
        }

        @JavascriptInterface
        public void dismissDialog() {
//            EventBus.getDefault().post(new EventWebEntity(1));
        }

        @JavascriptInterface
        public void onPublish(String sportRecordId) {
            publish(sportRecordId);
        }

        @JavascriptInterface
        public void onShare(String sportRecordId) {
            share(sportRecordId);
        }

        @JavascriptInterface
        public void getMoving() {
            onMoving();
        }

        @JavascriptInterface
        public void shareBtn(String activityInfo) {
            LogUtil.e("activityInfo", activityInfo.toString() + "-----");
            onShareBtn(activityInfo, 1);
        }

        @JavascriptInterface
        public void shareInfoBtn(String activityInfo) {
            LogUtil.e("activityInfo", activityInfo.toString() + "-----");
            onShareBtn(activityInfo, 2);
        }

        @JavascriptInterface
        public void shareTemporaryActivityBtn(String activityInfo) {
            LogUtil.e("activityInfo", activityInfo.toString() + "-----");
            onShareBtn(activityInfo, 3);
        }

        @JavascriptInterface
        public void pathToggle() {
            onPathToggle();
        }

        @JavascriptInterface
        public void skipUser(String id) {
            onSkipUser(id);
        }

        @JavascriptInterface
        public void navGoInformationDetail(String informationId) {
            information(informationId);
        }

        @JavascriptInterface
        public void inviteFriend() {
            invitFriend();
        }
    }

    public static void invitFriend() {
        activity.startActivity(new Intent(activity, InviteFriendsActivity.class));
    }

    public static void information(String informationId) {
        Intent intent = new Intent(activity, ReceiveLikedActivity.class);
        intent.putExtra("dynamicId", informationId);
        intent.putExtra("dynamicFlag", 1);
        activity.startActivity(intent);
    }

    public static void onMoving() {
        activity.runOnUiThread(new Runnable() {
            public void run() {
                handler.sendEmptyMessage(3);
            }
        });
    }

    public static void onShareBtn(String activityInfo, int type) {
        activity.runOnUiThread(new Runnable() {
            public void run() {
                Message msg = new Message();
                Bundle bundle = new Bundle();
                bundle.putString("activityInfo", activityInfo);
                bundle.putInt("type", type);
                msg.what = 2;
                msg.setData(bundle);
                handler.sendMessage(msg);
            }
        });
    }

    public static void share(String sportRecordId) {
        activity.runOnUiThread(new Runnable() {
            public void run() {
                Message msg = new Message();
                Bundle bundle = new Bundle();
                bundle.putString("sportRecordId", sportRecordId);
                msg.what = 1;
                msg.setData(bundle);
                handler.sendMessage(msg);
            }
        });
    }

    public static void publish(String sportRecordId) {
        Intent intent = new Intent(activity, PublishStatusActivity.class);
        intent.putExtra("motionId", sportRecordId);
        intent.putExtra("PUBLISH_FLAG", 1);
        activity.startActivity(intent);
    }

    public static void onSkipUser(String id) {
        Intent intent = new Intent(activity, MyHomeActivityV2.class);
        intent.putExtra(ActivityCompat.USER_ID, id);
        activity.startActivity(intent);
    }

    /**
     * 领取奖品
     */
    public static void onPathToggle() {
        EventBus.getDefault().post(new EventBusEntity(103));
        onClose();
    }

    public static void onClose() {
        activity.finish();
    }

    @OnClick({R.id.top_btn_left})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.top_btn_left:
                finish();
                break;
        }
    }

    private static Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1:
                    Bundle bundle = msg.getData();
                    String sportRecordId = bundle.getString("sportRecordId");
                    SharePoppupWindow sharePoppupWindow = SharePoppupWindow.getInstance(activity, "我在无涯运动跑步，今天离长征会师更进一步。",
                            "体验不一样的长征路，与我一起挑战吧！", String.format(Constant.SPORTS_DETAILS2, sportRecordId, "WEB"));
                    sharePoppupWindow.show();
                    break;
                case 2:
                    Bundle bundle1 = msg.getData();
                    String activityInfo = bundle1.getString("activityInfo");
                    int type = bundle1.getInt("type", 1);
                    if (type == 1) {
                        WebViewH5Entity h5Entity = JsonUtils.fromJson(activityInfo, WebViewH5Entity.class);
                        if (h5Entity != null) {
                            String sChallenge = "我正在挑战%skm目标赛，邀请您一起挑战！";
                            SharePoppupWindow sharePoppupWindow2 = SharePoppupWindow.getInstance(activity,
                                    String.format(sChallenge, h5Entity.activityAims),
                                    h5Entity.activityName,
                                    String.format(Constant.ACTIVITY_SEC_H5, h5Entity.activityId, UserAPI.getUserToken(), "WEB"));
                            sharePoppupWindow2.show();
                        }
                    } else if (type == 2) {
                        WebViewH5Entity h5Entity = JsonUtils.fromJson(activityInfo, WebViewH5Entity.class);
                        if (h5Entity != null) {
                            String sChallenge = h5Entity.informationTitle;
                            SharePoppupWindow sharePoppupWindow2 = SharePoppupWindow.getInstance(activity,
                                    String.format(sChallenge, h5Entity.informationTitle),
                                    h5Entity.informationTitle,
                                    String.format(Constant.NEWS_DETAILS_SHARE, h5Entity.informationId, UserAPI.getUserToken(), "WEB"));
                            sharePoppupWindow2.show();
                        }
                    } else if (type == 3) {
                        WebViewH5Entity h5Entity = JsonUtils.fromJson(activityInfo, WebViewH5Entity.class);
                        if (h5Entity != null) {
                            String sChallenge = h5Entity.shareTitle;
                            String url = Constant.BASE_HOST_H5 + h5Entity.shareUrl;
                            SharePoppupWindow sharePoppupWindow2 = SharePoppupWindow.getInstance(activity,
                                    String.format(sChallenge, h5Entity.shareTitle),
                                    h5Entity.shareDescribe,
                                    url);
                            sharePoppupWindow2.show();
                        }
                    }
                    break;
                case 3:
                    SportsPoppupWindow.getInstance(activity).show();
                    break;
            }
            return false;
        }
    });

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }


    class MyDownloadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype, long contentLength) {
            // TODO Auto-generated method stub

        }

    }

    /**
     * 有几个类要说明下：
     * <p>
     * MyChromeViewClient
     * 继承WebChromeClient重写了几个关键方法。其中有三个重载方法openFileChooser，用来兼容不同的Andorid版本
     * ，以防出现NoSuchMethodError异常。
     * 另外一个类UploadHandler，起到一个解耦合作用，它相当于WebChromeClient和Web网页端的一个搬运工兼职翻译
     * ，解析网页端传递给WebChromeClient的动作
     * ，然后将onActivityResult接收用户选择的文件传递给司机ValueCallback
     * 。WebChromeClient提供了一个Web网页端和客户端交互的通道，而UploadHandler就是用来搬砖的~。
     * UploadHandler有个很重要的成员变量：ValueCallback<Uri>
     * mUploadMessage。ValueCallback是WebView留下来的一个回调
     * ，就像是WebView的司机一样，当WebChromeClient和UploadHandler合作将文件选择后
     * ，ValueCallback开始将文件给WebView，告诉WebView开始干活了，砖头已经运回来了，你可以盖房子了。
     */
    class MyChromeViewClient extends WebChromeClient {

        @Override
        public void onCloseWindow(WebView window) {
            WebActivity.this.finish();
            super.onCloseWindow(window);
        }

        public void onProgressChanged(WebView view, final int progress) {
            activity.showDialog();
            if (progress == 100) {
                activity.dismissDialog();
            }
            super.onProgressChanged(view, progress);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message,
                                 final JsResult result) {

            new AlertDialog.Builder(WebActivity.this)
                    .setTitle("提示信息")
                    .setMessage(message)
                    .setPositiveButton(android.R.string.ok,
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    result.confirm();
                                }
                            }).setCancelable(false).create().show();
            return true;
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message,
                                   final JsResult result) {

            new AlertDialog.Builder(WebActivity.this)
                    .setTitle("提示信息")
                    .setMessage(message)
                    .setPositiveButton(android.R.string.ok,
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    result.confirm();
                                }
                            })
                    .setNegativeButton(android.R.string.cancel,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    result.cancel();
                                }
                            }).setCancelable(false).create().show();
            return true;

        }

        // Android 2.x
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, "");
        }

        // Android 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                    String acceptType) {
            openFileChooser(uploadMsg, "", "filesystem");
        }

        // Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                    String acceptType, String capture) {

            mUploadHandler = new UploadHandler(new Controller());
            mUploadHandler.openFileChooser(uploadMsg, acceptType, capture);
        }

        // For Android 5.0+
        public boolean onShowFileChooser(WebView webView,
                                         ValueCallback<Uri[]> filePathCallback,
                                         WebChromeClient.FileChooserParams fileChooserParams) {
            String[] acceptTypes = fileChooserParams.getAcceptTypes();
            openFileChooserImplForAndroid5(filePathCallback, acceptTypes[0]);
            return true;
        }

    }

    private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg, String acceptType) {
        mUploadMessageForAndroid5 = uploadMsg;
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType(acceptType);

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "选择图片");
        System.out.println("-----------调用");
        startActivityForResult(chooserIntent,
                FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
    }

    // copied from android-4.4.3_r1/src/com/android/browser/UploadHandler.java

    class UploadHandler {
        /*
         * The Object used to inform the WebView of the file to upload.
         */
        private ValueCallback<Uri> mUploadMessage;
        private String mCameraFilePath;
        private boolean mHandled;
        private boolean mCaughtActivityNotFoundException;
        private Controller mController;

        public UploadHandler(Controller controller) {
            mController = controller;
        }

        public String getFilePath() {
            return mCameraFilePath;
        }

        boolean handled() {
            return mHandled;
        }

        public void onResult(int resultCode, Intent intent) {
            if (resultCode == Activity.RESULT_CANCELED
                    && mCaughtActivityNotFoundException) {
                // Couldn't resolve an activity, we are going to try again so
                // skip
                // this result.
                mCaughtActivityNotFoundException = false;
                return;
            }
            Uri result = (intent == null || resultCode != Activity.RESULT_OK) ? null
                    : intent.getData();

            // As we ask the camera to save the result of the user taking
            // a picture, the camera application does not return anything other
            // than RESULT_OK. So we need to check whether the file we expected
            // was written to disk in the in the case that we
            // did not get an intent returned but did get a RESULT_OK. If it
            // was,
            // we assume that this result has came back from the camera.
            if (result == null && intent == null
                    && resultCode == Activity.RESULT_OK) {
                File cameraFile = new File(mCameraFilePath);
                if (cameraFile.exists()) {
                    result = Uri.fromFile(cameraFile);
                    // Broadcast to the media scanner that we have a new photo
                    // so it will be added into the gallery for the user.
                    mController.getActivity().sendBroadcast(
                            new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                    result));
                }
            }
            mUploadMessage.onReceiveValue(result);
            mHandled = true;
            mCaughtActivityNotFoundException = false;
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                    String acceptType, String capture) {
            final String imageMimeType = "image/*";
            final String videoMimeType = "video/*";
            final String audioMimeType = "audio/*";
            final String mediaSourceKey = "capture";
            final String mediaSourceValueCamera = "camera";
            final String mediaSourceValueFileSystem = "filesystem";
            final String mediaSourceValueCamcorder = "camcorder";
            final String mediaSourceValueMicrophone = "microphone";
            // According to the spec, media source can be 'filesystem' or
            // 'camera' or 'camcorder'
            // or 'microphone' and the default value should be 'filesystem'.
            String mediaSource = mediaSourceValueFileSystem;
            if (mUploadMessage != null) {
                // Already a file picker operation in progress.
                return;
            }
            mUploadMessage = uploadMsg;
            // Parse the accept type.
            String params[] = acceptType.split(";");
            String mimeType = params[0];
            if (capture.length() > 0) {
                mediaSource = capture;
            }
            if (capture.equals(mediaSourceValueFileSystem)) {
                // To maintain backwards compatibility with the previous
                // implementation
                // of the media capture API, if the value of the 'capture'
                // attribute is
                // "filesystem", we should examine the accept-type for a MIME
                // type that
                // may specify a different capture value.
                for (String p : params) {
                    String[] keyValue = p.split("=");
                    if (keyValue.length == 2) {
                        // Process key=value parameters.
                        if (mediaSourceKey.equals(keyValue[0])) {
                            mediaSource = keyValue[1];
                        }
                    }
                }
            }
            // Ensure it is not still set from a previous upload.
            mCameraFilePath = null;
            if (mimeType.equals(imageMimeType)) {
                if (mediaSource.equals(mediaSourceValueCamera)) {
                    // Specified 'image/*' and requested the camera, so go ahead
                    // and launch the
                    // camera directly.
                    startActivity(createCameraIntent());
                    return;
                } else {
                    // Specified just 'image/*', capture=filesystem, or an
                    // invalid capture parameter.
                    // In all these cases we show a traditional picker filetered
                    // on accept type
                    // so launch an intent for both the Camera and image/*
                    // OPENABLE.
                    Intent chooser = createChooserIntent(createCameraIntent());
                    chooser.putExtra(Intent.EXTRA_INTENT,
                            createOpenableIntent(imageMimeType));
                    startActivity(chooser);
                    return;
                }
            } else if (mimeType.equals(videoMimeType)) {
                if (mediaSource.equals(mediaSourceValueCamcorder)) {
                    // Specified 'video/*' and requested the camcorder, so go
                    // ahead and launch the
                    // camcorder directly.
                    startActivity(createCamcorderIntent());
                    return;
                } else {
                    // Specified just 'video/*', capture=filesystem or an
                    // invalid capture parameter.
                    // In all these cases we show an intent for the traditional
                    // file picker, filtered
                    // on accept type so launch an intent for both camcorder and
                    // video/* OPENABLE.
                    Intent chooser = createChooserIntent(createCamcorderIntent());
                    chooser.putExtra(Intent.EXTRA_INTENT,
                            createOpenableIntent(videoMimeType));
                    startActivity(chooser);
                    return;
                }
            } else if (mimeType.equals(audioMimeType)) {
                if (mediaSource.equals(mediaSourceValueMicrophone)) {
                    // Specified 'audio/*' and requested microphone, so go ahead
                    // and launch the sound
                    // recorder.
                    startActivity(createSoundRecorderIntent());
                    return;
                } else {
                    // Specified just 'audio/*', capture=filesystem of an
                    // invalid capture parameter.
                    // In all these cases so go ahead and launch an intent for
                    // both the sound
                    // recorder and audio/* OPENABLE.
                    Intent chooser = createChooserIntent(createSoundRecorderIntent());
                    chooser.putExtra(Intent.EXTRA_INTENT,
                            createOpenableIntent(audioMimeType));
                    startActivity(chooser);
                    return;
                }
            }
            // No special handling based on the accept type was necessary, so
            // trigger the default
            // file upload chooser.
            startActivity(createDefaultOpenableIntent());
        }

        private void startActivity(Intent intent) {
            try {
                mController.getActivity().startActivityForResult(intent,
                        Controller.FILE_SELECTED);
            } catch (ActivityNotFoundException e) {
                // No installed app was able to handle the intent that
                // we sent, so fallback to the default file upload control.
                try {
                    mCaughtActivityNotFoundException = true;
                    mController.getActivity().startActivityForResult(
                            createDefaultOpenableIntent(),
                            Controller.FILE_SELECTED);
                } catch (ActivityNotFoundException e2) {
                    // Nothing can return us a file, so file upload is
                    // effectively disabled.
                    Toast.makeText(mController.getActivity(),
                            "File uploads are disabled.", Toast.LENGTH_LONG)
                            .show();
                }
            }
        }

        private Intent createDefaultOpenableIntent() {
            // Create and return a chooser with the default OPENABLE
            // actions including the camera, camcorder and sound
            // recorder where available.
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            Intent chooser = createChooserIntent(createCameraIntent(),
                    createCamcorderIntent(), createSoundRecorderIntent());
            chooser.putExtra(Intent.EXTRA_INTENT, i);
            return chooser;
        }

        private Intent createChooserIntent(Intent... intents) {
            Intent chooser = new Intent(Intent.ACTION_CHOOSER);
            chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
            chooser.putExtra(Intent.EXTRA_TITLE, "Choose file for upload");
            return chooser;
        }

        private Intent createOpenableIntent(String type) {
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType(type);
            return i;
        }

        private Intent createCameraIntent() {
            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File externalDataDir = Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
            File cameraDataDir = new File(externalDataDir.getAbsolutePath()
                    + File.separator + "browser-photos");
            cameraDataDir.mkdirs();
            mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator
                    + System.currentTimeMillis() + ".jpg";
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(new File(mCameraFilePath)));
            return cameraIntent;
        }

        private Intent createCamcorderIntent() {
            return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        }

        private Intent createSoundRecorderIntent() {
            return new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
        }
    }

    class Controller {

        final static int FILE_SELECTED = 4;

        Activity getActivity() {
            return WebActivity.this;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {

        if (requestCode == Controller.FILE_SELECTED) {
            // Chose a file from the file picker.
            if (mUploadHandler != null) {
                mUploadHandler.onResult(resultCode, intent);
            }
        } else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
            if (null == mUploadMessageForAndroid5)
                return;
            Uri result = (intent == null || resultCode != Activity.RESULT_OK) ? null
                    : intent.getData();
            System.out.println("-----------界面执行了回调" + (result == null));
            if (result != null) {
                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{result});
            } else {
                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{});
            }
            mUploadMessageForAndroid5 = null;
        }
        super.onActivityResult(requestCode, resultCode, intent);
    }
}
